package cn.itsource.org.controller;

import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.basic.utils.PageResult;
import cn.itsource.org.domain.Department;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//@CrossOrigin
//@Controller
@RestController// 就是 @Controller+ @ResponseBody
@RequestMapping("/dept")
public class DepartmentController {
    /*
        1.怎么测试
        2.没一个方法上面都有 @ResponseBody
        3.返回一个OK？ 报错如何处理
        4.连接地址的问题
        httpClient

     */


    @Autowired
    private IDepartmentService departmentService;

    //传对象就用@RequestBody  从请全体里面去获取对象的属性值 并且封装到 department 里面
    //@RequestMapping(value = "/saveOrUpdate",method = RequestMethod.PUT)
    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Department department){
        System.out.println(department);
        try {
            if (department.getId()==null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
        return new AjaxResult();
    }

    //@RequestMapping(value = "/del",method = RequestMethod.DELETE)
    //http://localhost/dept/10
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
        } catch (Exception e) {
            return new AjaxResult(e.getMessage());
        }
        return new AjaxResult();
    }



    //@RequestMapping(value = "/findOne" ,method = RequestMethod.DELETE)//查询单条的时候 只是接收 post请求
    @GetMapping("/{id}")
    public Department findOne(@PathVariable("id") Long id){
        return departmentService.queryById(id);
    }
    //@RequestMapping("/findAll")
    @GetMapping
    public List<Department> findAll(){
        return departmentService.query();
    }


    @PostMapping
    public PageResult<Department> findAll(@RequestBody DepartmentQuery query){
        System.out.println(query);
        return departmentService.queryPage(query);
    }
    @PostMapping("/testFindAll")
    public List<Department> testFindAll(){
        //直接查询所有

        return  departmentService.testFindAll();
    }
    /*
        批量删除
            前端给过的数组 [56,55,54,53]
            后台对应的接收形式 可以是数组 可以是 集合
     */
    @PatchMapping
    public AjaxResult deletePatch(@RequestBody List<Long> ids){
        System.out.println(ids);
        try {
          departmentService.deletes(ids);
        } catch (Exception e) {
            return new AjaxResult(e.getMessage());
        }
        return new AjaxResult();
    }
}
